package edu.geektime.jiangfan.chapter02.netty01;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.Objects;
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;

@Slf4j
public class HttpHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        FullHttpRequest fullHttp = (FullHttpRequest) msg;
        try {
            String uri = fullHttp.uri();
            if (uri.contains("test")) {
                handlerTest(fullHttp, ctx, "test 请求:" + new Date());
            } else {
                handlerTest(fullHttp, ctx, "默认请求");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }

    private void handlerTest(FullHttpRequest fullHttp, ChannelHandlerContext ctx, String msg) {
        FullHttpResponse fullHttpResponse = null;
        try {
            String value = msg;
            fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
            fullHttpResponse.headers().set("Content-Type", "application/json");
            fullHttpResponse.headers().setInt("Content-Length", fullHttpResponse.content().readableBytes());
        } catch (Exception e) {
            log.error("执行报错:{}",e.getMessage());
            fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.NO_CONTENT);
        } finally {
            if (Objects.nonNull(fullHttpResponse)) {
                if (!HttpUtil.isKeepAlive(fullHttp)) {
                  ctx.write(fullHttpResponse).addListener(ChannelFutureListener.CLOSE);
                } else {
                  fullHttpResponse.headers().set(CONNECTION,KEEP_ALIVE);
                  ctx.write(fullHttpResponse);
                }
                ctx.flush();
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
